package com.atguigu.day3;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

//实现线程的方式一
class MyThread1 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
        }
    }
}

//实现线程的方式二
class MyThread2 implements Runnable {
    @Override
    public void run() {
        for (char c = 'a'; c <= 'z'; c++) {
            System.out.println(c);
        }
    }
}

//实现线程的方式三
class MyThread3 implements Callable<String> {
    @Override
    public String call() throws Exception {
        TimeUnit.SECONDS.sleep(5);
        return "Callable实现的线程!";
    }
}

public class RunableAndCallable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //继承Thread线程
       /*MyThread1 myThread1 = new MyThread1();
        Thread thread1 = new Thread(myThread1,"A");
        thread1.start();*/

        //实现Runable接口的
        /*MyThread2 myThread2 = new MyThread2();
        Thread thread2 = new Thread(myThread2,"B");
        thread2.start();*/

        //创建Callable的实例
        MyThread3 myThread3 = new MyThread3();
        //用FutureTask类来包装Callable对象
        FutureTask<String> futureTask = new FutureTask<>(myThread3);
        //创建多线程
        Thread thread3 = new Thread(futureTask, "C");
        Thread thread4 = new Thread(futureTask,"D");
        thread3.start();
        thread4.start();

        System.out.println(Thread.currentThread().getName()+"\t"+"task over");

        //futureRask.get()方法必须放最后，不然会造成线程阻塞
        System.out.println(futureTask.get());
        System.out.println(futureTask.get());
    }
}
